<template>
    <ValidateFrom @from-submit="onSubmitForm">
        <label for="emailInput">Email address</label>
        <ValidateInput type="email" inputId="emailInput" :rules="emailRules" v-model="formData.emailVal"></ValidateInput>
        <label for="nickName">nickName</label>
        <ValidateInput type="text" inputId="nickName" :rules="nickNameRules" v-model="formData.nickName"></ValidateInput>
        <label for="passwordInput">Password</label>
        <ValidateInput type="password" inputId="passwordInput" :rules="passwordRules" v-model="formData.password"></ValidateInput>
        <label for="repeatPassword">Repeat Password</label>
        <ValidateInput type="password" inputId="repeatPassword" :rules="repeatPasswordRules" v-model="formData.repeatPassword"></ValidateInput>
    </ValidateFrom>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import { useRouter } from 'vue-router'
import ValidateInput, { RulesProp } from '../components/ValidateInput.vue'
import ValidateFrom from '../components/ValidateFrom.vue'
import createMessage from '../components/createMessage'
import axios from 'axios';

const formData = reactive({
    emailVal: '',
    nickName: '',
    password: '',
    repeatPassword: ''
})
const router = useRouter()

const emailRules: RulesProp = [
  { type: 'required', message: '电子邮件地址不能为空'},
  { type: 'email', message: '请输入正确的邮箱格式'}
]
const nickNameRules: RulesProp = [
  { type: 'required', message: '昵称不能为空'},
]
const passwordRules: RulesProp = [
  { type: 'required', message: '密码不能为空'},
  { type: 'range', message: '密码不能少于6位，不能多于12位'}
]
const repeatPasswordRules: RulesProp = [
  { type: 'required', message: '重复密码不能为空'},
  { type: 'custom', 
    validator: () => {
        return formData.repeatPassword === formData.password
    },
    message: '密码不相同'}
]

const onSubmitForm = (result: boolean) => {
    if (result) {
        const payload = {
            email: formData.emailVal,
            password: formData.password,
            nickName: formData.nickName
        }
        axios.post('/users', payload).then(() => {
            createMessage('注册成功', 'success')
            router.push('/login')
        }).catch((err) => {
            console.log(err)
        })
    }
}
</script>